/**
 * 32. 最长有效括号
 * https://leetcode-cn.com/problems/longest-valid-parentheses/
 */

/**
 * @param {string} s
 * @return {number}
 */
function longestValidParentheses(s) {
  const stack = new Array(s.length);
  let top = -1;
  let max = 0;
  for (let i = 0; i < s.length; i += 1) {
    if (s[i] === '(') {
      top += 1;
      stack[top] = i;
    } else {
      // eslint-disable-next-line no-lonely-if
      if (top >= 0 && s[stack[top]] === '(') {
        top -= 1;
        if (top >= 0) {
          max = Math.max(max, i - stack[top]);
        } else {
          max = i + 1;
        }
      } else {
        top += 1;
        stack[top] = i;
      }
    }
  }
  return max;
}

console.log(longestValidParentheses('(()') === 2);
console.log(longestValidParentheses(')()())') === 4);
console.log(longestValidParentheses('') === 0);
